package com.content.scaffold.common.mybatis.query;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.Min;

/**
 * 分页查询参数
 * @author xiaojl
 */
@Data
public class PageQuery {
   /**当前页码", example = "1"**/
    @Min(value = 1, message = "页码不能小于1")
    private Integer page = 1;

   /**每页数量", example = "10"**/
    @Min(value = 1, message = "每页数量不能小于1")
    private Integer size = 10;

   /**排序字段", example = "createTime"**/
    private String sort;

   /**排序方向", example = "desc", allowableValues = "asc,desc"**/
    private String order = "desc";

   /**查询参数"**/
    private BaseQueryParams params;

    /**
     * 转换为MyBatis Plus的Page对象
     */
    public <T> Page<T> toPage() {
        Page<T> page = new Page<>(this.page, this.size);

        if (StringUtils.isNotBlank(sort)) {
            String sortField = com.content.scaffold.common.utils.StringUtils.camelToUnderline(sort);
            if ("asc".equalsIgnoreCase(order)) {
                page.addOrder(OrderItem.asc(sortField));
            } else {
                page.addOrder(OrderItem.desc(sortField));
            }
        }

        return page;
    }

    /**
     * 多字段排序支持
     */
    public <T> Page<T> toMultiSortPage() {
        Page<T> page = new Page<>(this.page, this.size);

        if (StringUtils.isNotBlank(sort)) {
            String[] sortFields = sort.split(",");
            String[] orders = order.split(",");

            for (int i = 0; i < sortFields.length; i++) {
                String field = com.content.scaffold.common.utils.StringUtils.camelToUnderline(sortFields[i]);
                String dir = i < orders.length ? orders[i] : "desc";

                if ("asc".equalsIgnoreCase(dir)) {
                    page.addOrder(OrderItem.asc(field));
                } else {
                    page.addOrder(OrderItem.desc(field));
                }
            }
        }

        return page;
    }
}

